package com.ruoyi.common.utils.python;

import com.ruoyi.common.exception.UtilException;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Slf4j
public class PythonUtil {

    public static List<String> callPython(String[] args) {
//        log.info(Arrays.toString(args));
        List<String> list = new ArrayList<>();
        try {
            Process proc = Runtime.getRuntime().exec(args);
            BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream(), "gb2312"));//解决中文乱码，参数可传中文
            String line;
            while ((line = in.readLine()) != null) {
//                log.info(line);
                list.add(line);
            }
            int exitVal = proc.waitFor();
//            log.info("python执行结果:{}", exitVal);
            if (exitVal != 0) {
//                log.error("python执行中断");
                throw new UtilException("python执行过程中断");
            }
            in.close();
        } catch (IOException | InterruptedException e) {
//            log.error("python执行过程中断,错误原因:", e);
            throw new UtilException("python执行过程中断");
        }
        return list;
    }

    public static List<String> getPythonMethodNamesByContent(String content) {

        // 正则表达式匹配Python方法定义，排除main方法
        String methodPattern = "(?m)^def (?!main\\()(\\w+)\\(";

        Pattern pattern = Pattern.compile(methodPattern);
        Matcher matcher = pattern.matcher(content);

        // 提取并打印所有方法名（不包括main方法）
        List<String> methodNames = new ArrayList<>();
        while (matcher.find()) {
            String methodName = matcher.group(1);
            methodNames.add(methodName);
//            log.info("methodName:{}", methodName);
        }
        return methodNames;
    }
}
